package eirkdbd.lab1.gui.tab;

import java.awt.Dimension;
import java.util.Iterator;

import javax.swing.BoxLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;

import eirkdbd.lab1.log.MainTable;
import eirkdbd.lab1.log.TableObject;
import eirkdbd.lab1.log.model.TableModel;

public abstract class TableTab<T extends TableObject> extends AbstractTab {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9000L;

	protected MainTable table;
	protected JTable jTable;
	
	protected TableModel<T> model;
	
	@Override
	protected final void init() {
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		initSelectionPane();
		initButtonPane();
		initTablePane();
		
		initModel();
	}
	
	protected abstract void initSelectionPane();
	protected abstract void initButtonPane();
	
	private final void initTablePane() {
		JScrollPane pane;
		initTable();
		initJTable();
		pane = new JScrollPane(jTable);
	    pane.setPreferredSize(new Dimension(800, 100));
	    
	    add(pane);
	}
	
	/**
	 * Initializes table (use super.table).
	 */
	protected abstract void initTable();
	
	private final void initJTable() {
		DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
        dtcr.setHorizontalAlignment(SwingConstants.CENTER);
        
	    jTable = new JTable(table);
	    
	    for(int i = 0; i < jTable.getColumnCount(); i++) {
			jTable.getColumnModel().getColumn(i).setCellRenderer(dtcr);
		}
		
        jTable.setFillsViewportHeight(true);
        //jTable.getSelectionModel().addListSelectionListener(new TableListener());
        jTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        changeColumnSizes();
	}
	
	/**
	 * <p>Changes column sizes of jTable (use super.jTable).</p>
	 * Example:<br>
	 * <code>jTable.getColumnModel().getColumn(0).setWidth(30);</code>
	 * <p>All column sizes must be changed to see result of this method.</p>
	 */
	protected void changeColumnSizes() {}
	
	protected abstract void initModel();
	
	@Override
	public void dataToUi() {
		refreshTable();
	}
	
	private void refreshTable() {
		table.clear();
		Iterator<T> it = model.getModelObjects();
		while(it.hasNext()) {
			table.addRow(it.next().toObject());
		}
		jTable.revalidate();
		jTable.repaint();
	}
}
